﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.IO;
using 卷书.Utils;
using static 卷书.Global;

namespace 卷书.UserControls
{
    /// <summary>
    /// LibraryView.xaml 的交互逻辑
    /// </summary>
    public partial class LibraryView : UserControl
    {


        public static readonly DependencyProperty LibraryNameProperty = DependencyProperty.Register(
    "LibraryName", typeof(string), typeof(LibraryView), new PropertyMetadata(""));

        public string LibraryName
        {
            get { return (string)GetValue(LibraryNameProperty); }
            set
            {
                SetValue(LibraryNameProperty, value);
            }
        }



        public static readonly DependencyProperty LibraryListProperty = DependencyProperty.Register(
"LibraryList", typeof(List<LibraryFile>), typeof(LibraryView), new PropertyMetadata(null));

        public List<LibraryFile> LibraryList
        {
            get { return (List<LibraryFile>)GetValue(LibraryListProperty); }
            set
            {
                SetValue(LibraryListProperty, value);
                ItemsControl.Items.Refresh();
            }
        }



        public LibraryView(string name)
        {
            InitializeComponent();
            LibraryName = name;
            LibraryList = LibraryStream.Read(LibraryName);
            this.DataContext = this;
            ItemsControl.Items.Refresh();
        }

        public void RefreshBinding()
        {
            ItemsControl.Items.Refresh();
        }

        private void RenameFileName(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            ContextMenu contextMenu = menuItem.Parent as ContextMenu;
            var textBox = LogicalTreeHelper.FindLogicalNode(contextMenu.PlacementTarget as Border, "tb");
            if (textBox != null)
            {
                TextBox tb = textBox as TextBox;
                tb.Visibility = Visibility.Visible;
                tb.Focus();
                tb.SelectAll();
            }

        }

        private void RemoveFile(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            ContextMenu contextMenu = menuItem.Parent as ContextMenu;
            TextBox tb = LogicalTreeHelper.FindLogicalNode(contextMenu.PlacementTarget as Border, "tb") as TextBox;
            string hash = tb.Tag.ToString();
            var lb = LibraryList.Where(arg => arg.hash == hash).FirstOrDefault();
            LibraryStream.RemoveByName(LibraryName, lb.hash);//保存到 xml 中
            LibraryList.Remove(lb);
            ItemsControl.Items.Refresh();
            
            
        }



        private void filetb_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            tb.Visibility = Visibility.Collapsed;
            string hash = tb.Tag.ToString();
            var lb = LibraryList.Where(arg => arg.hash == hash).FirstOrDefault();
            string path = Path.GetDirectoryName(lb.filepath);
            string oldname = lb.filename;
            string ext = Path.GetExtension(lb.filepath);
            string oldpath = Path.Combine(path, lb.filename + ext);
            if (IsEscape) tb.Text = oldname;
            if (!IsEscape && tb.Text != oldname)
            {
                
                //替换掉禁止的字符
                foreach (char item in BANFILECHAR) { tb.Text = tb.Text.Replace(item.ToString(), ""); }
                string newpath = Path.Combine(path, tb.Text + ext);
                if (File.Exists(newpath) && Path.GetDirectoryName(newpath) == Path.GetDirectoryName(oldpath))
                {
                    StatusMessage = new StringBuilder("改名失败，文件已存在");
                    tb.Text = oldname;
                }
                else if (tb.Text == "")
                {
                    StatusMessage = new StringBuilder("不可为空！");
                    tb.Text = oldname;
                }
                else
                {

                    for (int i = 0; i < LibraryList.Count; i++)
                    {
                        if (LibraryList[i].hash == hash)
                        {
                            LibraryList[i].filepath = newpath;
                            LibraryList[i].filename = tb.Text;
                            File.Move(oldpath, newpath);//重命名文件
                            LibraryStream.RenameFile(LibraryName,hash, tb.Text, newpath);//保存到 xml 中
                            break;
                        }
                    }
                    ItemsControl.Items.Refresh();
                }
            }
        }

        private void tb_LostFocus(object sender, RoutedEventArgs e)
        {

            TextBox tb = sender as TextBox;
            tb.Visibility = Visibility.Collapsed;
            //改变了 LibraryName 才修改
            if (IsEscape) tb.Text = LibraryName;
            if (!IsEscape && tb.Text != LibraryName)
            {
                if (Libraries.Select(arg => arg.Name).ToList().Contains(tb.Text))
                {
                    StatusMessage = new StringBuilder("存在重复名称！");
                    tb.Text = LibraryName;
                }
                else if (tb.Text == "")
                {
                    StatusMessage = new StringBuilder("不可为空！");
                    tb.Text = LibraryName;
                }
                else
                {
                    LibraryStream.RenameLibrary(LibraryName, tb.Text);
                    Global.Init();
                    LibraryName = tb.Text;
                    //保存到文件中
                }

            }

        }

        private void RenameLibraryName(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            ContextMenu contextMenu = menuItem.Parent as ContextMenu;
            var textBox = LogicalTreeHelper.FindLogicalNode(contextMenu.PlacementTarget as Grid, "tb");

            if (textBox != null)
            {
                TextBox tb = textBox as TextBox;
                tb.Visibility = Visibility.Visible;
                tb.Focus();
                tb.SelectAll();
            }

            


        }

        private void OpenPath(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            ContextMenu contextMenu = menuItem.Parent as ContextMenu;
            Border border = contextMenu.PlacementTarget as Border;
            string hash = border.Tag.ToString();
            var library = LibraryList.Where(arg => arg.hash == hash).FirstOrDefault();
            FileHelper.TryOpenSelectPath(library.filepath);

        }

        private bool IsEscape = false;

        private void tb_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            IsEscape = false;
            if (e.Key == Key.Enter)
            {
                tb_LostFocus(sender, null);
            }
            else if (e.Key == Key.Escape)
            {
                IsEscape = true;
                tb_LostFocus(sender, null);
            }

        }

        private void tb_PreviewKeyDown_1(object sender, KeyEventArgs e)
        {
            IsEscape = false;
            if (e.Key == Key.Enter)
            {
                filetb_LostFocus(sender, null);
            }
            else if (e.Key == Key.Escape)
            {
                IsEscape = true;
                filetb_LostFocus(sender, null);
            }

        }

        private void DeleteLibrary(object sender, RoutedEventArgs e)
        {
                MainWindow main = FileHelper.GetWindowByName("MainWindow") as MainWindow;
                //先删除弹出的这个对象
                CheckBox _cb = LogicalTreeHelper.FindLogicalNode(this, "cb") as CheckBox;
                if (!(bool)_cb.IsChecked)
                {
                    LibraryStream.DeleteByName(this.LibraryName);
                    main.LibrariesContainer.Children.Remove(this);
                    
                }
                //获取所有选中的对象
                var lvs = main.LibrariesContainer.Children.OfType<LibraryView>().ToList();
                for (int i = lvs.Count - 1; i >= 0; i--)
                {
                    CheckBox cb = LogicalTreeHelper.FindLogicalNode(lvs[i], "cb") as CheckBox;
                    if ((bool)cb.IsChecked)
                    {
                        LibraryStream.DeleteByName(lvs[i].LibraryName);
                        main.LibrariesContainer.Children.Remove(lvs[i]);
                    }
                }
                Global.Init();
            

        }

        private void UserControl_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Link;
            e.Handled = true;

        }

        private void UserControl_Drop(object sender, DragEventArgs e)
        {

            string[] dragdropFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            ImportFile(dragdropFiles);


        }

        public void ImportFile(string[] files)
        {
            if (LibraryList == null) LibraryList = new List<LibraryFile>();
            foreach (var file in files)
            {
                if (FileHelper.IsFile(file))
                {
                    FileInfo fileInfo = new FileInfo(file);
                    if (fileInfo.Extension.ToLower() == ".pdf")
                    {
                        string name = Path.GetFileNameWithoutExtension(file);
                        LibraryFile libraryFile = new LibraryFile(file);
                        if (!LibraryList.Select(arg => arg.hash).ToList().Contains(libraryFile.hash))
                        {
                            LibraryList.Add(libraryFile);
                            //入库

                        }
                    }

                }
            }
            ItemsControl.Items.Refresh();
            CheckBox cb = LogicalTreeHelper.FindLogicalNode(this, "cb") as CheckBox;
            cb.IsChecked = true;

            //保存到文件中
            LibraryStream.SaveLibraryFiles(LibraryName, LibraryList);
        }

        private void ImportFile(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog OpenFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            OpenFileDialog1.Title = "请选择文件";
            OpenFileDialog1.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            OpenFileDialog1.Filter = "pdf|*.pdf";
            OpenFileDialog1.FilterIndex = 1;
            OpenFileDialog1.RestoreDirectory = true;
            OpenFileDialog1.Multiselect = true;
            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] files = OpenFileDialog1.FileNames;
                ImportFile(files);
            }
        }

        private void rb_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            string hash = rb.Tag.ToString();
            MainWindow main = FileHelper.GetWindowByName("MainWindow") as MainWindow;
            var libraryFile = LibraryList.Where(arg => arg.hash == hash).FirstOrDefault();
            string fp = libraryFile.filepath;
            main.pdfViewer.Source = fp;
            main.pdfViewer.LibraryFile = libraryFile;
            main.pdfViewer.LibraryName = LibraryName;
            main.pdfViewer.scrollViewer.ScrollToTop();
        }
    }
}
